/***
 * @Author: 玄绮 shijiahansi@qq.com
 * @Date: 2024-05-03 18:30:37
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-05-18 12:11:04
 * @FilePath: \server\test\test_smtp\main.cpp
 * @Description:
 * @
 * @Copyright (c) 2024 by 玄绮, All Rights Reserved.
 */

#include <boost/algorithm/string/replace.hpp>
#include <fstream>
#include <iostream>
#include <random>
#include <smtp>
#include <string>


const std::string smtp_password = "mxwzlusjmjlkbffc";
const std::string username      = "shijiahansi@qq.com";

int generateRandomCode() {
    // 使用 C++11 的随机数引擎和分布
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(100000, 999999);  // 生成6位数

    return dis(gen);
}

std::string loadfile(std::string filepath) {
    std::ifstream fin(filepath, std::ios::binary);

    if (!fin.is_open()) {
        std::cerr << "Error opening file: " << filepath << std::endl;
        return "";
    }

    // 使用 std::stringstream 读取文件内容
    // std::stringstream buffer;
    // buffer << fin.rdbuf();
    // return buffer.str();

    // 或者使用 std::string 直接读取文件内容
    std::string content((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>());
    return content;
}

int main(int argc, char const* argv[]) {
    try {
        smtp::Mail email;
        smtp::SmtpSSL smt;
        smt.login(username, smtp_password);

        email.set_form(username);
        email.set_to("1915226120@qq.com");
        email.set_subject("测试");
        // email.add_attachfile(R"(D:\Users\SGA\Pictures\63839470691664.png)");

        auto code = std::to_string(generateRandomCode());

        auto templatecode = loadfile("./smtp/verification_code.html");
        for (size_t i = 0; i < code.length(); i++) {
            boost::algorithm::replace_all(templatecode, "${" + std::to_string(i) + "}", std::string(1, code[i]));
        }

        email.set_content(templatecode, "text/html");

        smt.mail(&email);
        smt.run();
        smt.quit();
    }
    catch (const std::exception& e) {
        std::cerr << e.what() << '\n';
    }

    return 0;
}